package com.ak.reggie.controller;

import com.ak.reggie.common.R;
import com.ak.reggie.dto.SetmealDto;
import com.ak.reggie.entity.Category;
import com.ak.reggie.entity.Setmeal;
import com.ak.reggie.service.CategoryService;
import com.ak.reggie.service.SetmealDishService;
import com.ak.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套菜管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套菜
     * @param setmealDto
     * @return
     * INSERT INTO setmeal ( id, category_id, name, price, status, code, description, image, create_time, update_time, create_user, update_user ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
     * INSERT INTO setmeal_dish ( id, setmeal_id, dish_id, name, price, copies, create_time, update_time, create_user, update_user ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true) //删除该套餐下的所有数据
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套菜信息：{}", setmealDto);

        setmealService.saveWithDish(setmealDto);
        return R.success("新增套菜成功");
    }

    /**
     * 套菜分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     * SELECT id,category_id,name,price,status,code,description,image,create_time,update_time,create_user,update_user FROM setmeal ORDER BY update_time DESC LIMIT ?
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //1、分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        //2、条件构造器对象
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行查询like模糊查询
        wrapper.like(name != null, Setmeal::getName, name);
        //添加排序条件，根据更新时间降序排列
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, wrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
//        List<SetmealDto> list = null;

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套菜
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true) //删除该套餐下的所有数据
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids：{}", ids);

        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     * 报错：java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.ak.reggie.common.R]
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status") //缓存套餐数据
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        wrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        wrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);
    }

}
